package com.example.finalhomework

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleObserver
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.finalhomework.cardgame.MainScreen_cardgame
import com.example.finalhomework.cardgame.PersonalInfoScreen
import com.example.finalhomework.cardgame.UpdateInfoScreen
import com.example.finalhomework.cardgame.ui.AdvancedCardGameScreen
import com.example.finalhomework.cardgame.ui.UserInfo
import com.example.finalhomework.cardgame.ui.loadUserInfo
import com.example.finalhomework.firsthomework.ManyHelloWorld
import com.example.finalhomework.musicplayer.MusicPlayerScreen
import com.example.finalhomework.secondhomework.SecondHomework
import com.example.finalhomework.thirdhomework.*
import com.example.finalhomework.ui.theme.FinalHomeworkTheme
import com.example.finalhomework.weather.City
import com.example.finalhomework.weather.WeatherCityScreen
import com.example.finalhomework.weather.WeatherScreen
import com.example.finalhomework.weather.WeatherViewModel
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class MainActivity : ComponentActivity() {
    private val viewModel: FifthViewModel by viewModels()
    private val weatherViewModel: WeatherViewModel by viewModels()
    private lateinit var timerLifecycleObserver: LifecycleObserver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("MainActivity", "onCreate called")
        timerLifecycleObserver = TimerLifecycleObserver(viewModel)
        lifecycle.addObserver(timerLifecycleObserver)

        // Request READ_EXTERNAL_STORAGE permission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Log.d("MainActivity", "Requesting READ_EXTERNAL_STORAGE permission")
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
        }

        createNotificationChannel() // 创建通知渠道

        setContent {
            FinalHomeworkTheme {
                RequestStoragePermission {
                    val navController = rememberNavController()
                    var receivedMessage by remember { mutableStateOf("") }
                    var mainScreenMessage by remember { mutableStateOf("") }
                    var cities by remember { mutableStateOf(listOf<City>()) }
                    val context = LocalContext.current

                    LaunchedEffect(Unit) {
                        Log.d("MainActivity", "Loading cities from raw resource")
                        cities = withContext(Dispatchers.IO) {
                            val str = weatherViewModel.readFileFromRaw(context, R.raw.citycode)
                            val gson = Gson()
                            val cityType = object : com.google.gson.reflect.TypeToken<List<City>>() {}.type
                            gson.fromJson(str, cityType)
                        }
                    }

                    NavHost(navController = navController, startDestination = "home") {
                        composable("home") { HomeScreen(navController) }
                        composable("manyhelloworld") { ManyHelloWorld(navController) }
                        composable("secondhomework") { SecondHomework(navController) }
                        composable("thirdhomework") {
                            MainScreen_3(
                                navController,
                                receivedMessage,
                                mainScreenMessage
                            ) { newMessage ->
                                mainScreenMessage = newMessage
                            }
                        }
                        composable("fifthactivity") { FifthScreen_3(navController, viewModel) }
                        composable("fourthactivity") { FourthScreen_3(navController) }
                        composable(
                            "secondactivity/{message}",
                            arguments = listOf(navArgument("message") { type = NavType.StringType })
                        ) { backStackEntry ->
                            val message = backStackEntry.arguments?.getString("message") ?: ""
                            SecondScreen_3(navController, message)
                        }
                        composable("thirdactivity") {
                            ThirdScreen_3(navController, onConfirmClick = { message ->
                                receivedMessage = message
                                navController.popBackStack("thirdhomework", false)
                            })
                        }

                        composable("cardgame") { MainScreen_cardgame(navController) }
                        composable("AdvancedCardGame") { AdvancedCardGameScreen(navController) }
                        composable("PersonalInfo") { PersonalInfoScreen(navController) }
                        composable(
                            "UpdateInfo/{name}/{gender}/{studentId}/{phone}/{email}/{hobbies}/{avatarUri}",
                            arguments = listOf(
                                navArgument("name") { type = NavType.StringType },
                                navArgument("gender") { type = NavType.StringType },
                                navArgument("studentId") { type = NavType.StringType },
                                navArgument("phone") { type = NavType.StringType },
                                navArgument("email") { type = NavType.StringType },
                                navArgument("hobbies") { type = NavType.StringType },
                                navArgument("avatarUri") { type = NavType.StringType } // 修改为 StringType
                            )
                        ) { backStackEntry ->
                            val name = backStackEntry.arguments?.getString("name") ?: ""
                            val gender = backStackEntry.arguments?.getString("gender") ?: ""
                            val studentId = backStackEntry.arguments?.getString("studentId") ?: ""
                            val phone = backStackEntry.arguments?.getString("phone") ?: ""
                            val email = backStackEntry.arguments?.getString("email") ?: ""
                            val hobbies = backStackEntry.arguments?.getString("hobbies") ?: ""
                            val avatarUri = backStackEntry.arguments?.getString("avatarUri") ?: ""
                            val userInfo = UserInfo(
                                name,
                                gender,
                                studentId,
                                phone,
                                email,
                                hobbies,
                                avatarUri,
                                0,
                                0
                            )
                            UpdateInfoScreen(navController, context, userInfo) { updatedUserInfo ->
                                // Update the user info in PersonalInfoScreen
                            }
                        }
                        composable("musicplayer") { MusicPlayerScreen(navController) }
                        composable("weathercityscreen") {
                            WeatherCityScreen(navController, weatherViewModel)
                        }
                        composable(
                            "weather/{cityCode}",
                            arguments = listOf(navArgument("cityCode") { type = NavType.StringType })
                        ) { backStackEntry ->
                            val cityCode = backStackEntry.arguments?.getString("cityCode") ?: ""
                            WeatherScreen(cityCode)
                        }
                    }
                }
            }
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Music Player Channel"
            val descriptionText = "Channel for music player notifications"
            val importance = NotificationManager.IMPORTANCE_LOW
            val channel = NotificationChannel("MUSIC_PLAYER_CHANNEL", name, importance).apply {
                description = descriptionText
            }
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
            Log.d("MainActivity", "Notification channel created")
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("MainActivity", "onPause called")
        viewModel.stopTimer()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("MainActivity", "onDestroy called")
        lifecycle.removeObserver(timerLifecycleObserver)
    }
}

@Composable
fun RequestStoragePermission(content: @Composable () -> Unit) {
    val context = LocalContext.current
    val permission = Manifest.permission.READ_MEDIA_AUDIO
    val permissionGranted = remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        )
    }

    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        permissionGranted.value = isGranted
        Log.d("RequestStoragePermission", "Permission granted: $isGranted")
    }

    if (permissionGranted.value) {
        content()
    } else {
        LaunchedEffect(Unit) {
            Log.d("RequestStoragePermission", "Requesting storage permission")
            launcher.launch(permission)
        }
    }
}